package com.js.rtu.fragment.second;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;

import com.js.rtu.R;
import com.js.rtu.base.BaseFragment;
import com.js.rtu.config.CmdConfig;
import com.js.rtu.config.IniConfig;
import com.js.rtu.util.BluetoothUtils;
import com.js.rtu.util.CmdUtils;
import com.js.rtu.util.ToastUtil;

import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 23_19多中心参数
 * 第 1 字节： 中心个数 n（含主中心， 第 1 个中心参
 * 数为主中心， 与数据标识 12、 13 功能一致）
 * 第 2-5 字节： 中心 1 IP
 * 第 6-7 字节： 中心 1 端口
 * 第 8 字节： 网络连接类型（参看“备注 1” ）
 * 第 9 字节： 使能标志（参看“备注 2” ）
 * … 第
 * 2*n-2*5 字节： 中心 n IP
 * 第 6*n-7*n 字节： 中心 n 端口
 * 第 8*n 字节： 网络连接类型（参看“备注 1” ）
 * 第 9*n 字节： 使能（参看“备注 2” ）
 * Created by zwz on 2020/6/22.
 */
public class Cmd_23_19Fragment extends BaseFragment {



    @BindView(R.id.rbtn_single)
    RadioButton rbtnSingle;
    @BindView(R.id.rbtn_muit)
    RadioButton rbtnMuit;
    @BindView(R.id.radio)
    RadioGroup radio;
    @BindView(R.id.edt_ip1)
    EditText edtIp1;
    @BindView(R.id.edt_port1)
    EditText edtPort1;
    @BindView(R.id.sp_list1)
    Spinner spList1;
    @BindView(R.id.cb_enalbe1)
    CheckBox cbEnalbe1;
    @BindView(R.id.ll_one)
    LinearLayout llOne;
    @BindView(R.id.edt_ip2)
    EditText edtIp2;
    @BindView(R.id.edt_port2)
    EditText edtPort2;
    @BindView(R.id.sp_list2)
    Spinner spList2;
    @BindView(R.id.cb_enalbe2)
    CheckBox cbEnalbe2;
    @BindView(R.id.ll_two)
    LinearLayout llTwo;


    public static Cmd_23_19Fragment newInstance() {
        Cmd_23_19Fragment fragment = new Cmd_23_19Fragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tab_second_cmd_23_19;
    }

    @Override
    protected void initView() {


        ArrayAdapter<String> mAdapter = new ArrayAdapter<>(_mActivity, android.R.layout.simple_spinner_dropdown_item, IniConfig.connectType_des);
        spList1.setAdapter(mAdapter);
        spList2.setAdapter(mAdapter);
        radio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rbtn_single:
                        llTwo.setVisibility(View.GONE);
                        break;
                    case R.id.rbtn_muit:
                        llTwo.setVisibility(View.VISIBLE);
                        break;
                }
            }
        });

    }


    private void set() {
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append(CmdConfig.CMD_23_19).append(" ");
        String ip1 = edtIp1.getText().toString();
        String port1 = edtPort1.getText().toString();
        String sp1 = String.format(Locale.CHINA, "%02d",
                Integer.parseInt(IniConfig.connectType_data.get(spList1.getSelectedItemPosition())));

        boolean enable1 = cbEnalbe1.isChecked();
        String ip2 = edtIp2.getText().toString();
        String port2 = edtPort2.getText().toString();
        String sp2 = String.format(Locale.CHINA, "%02d",
        Integer.parseInt(IniConfig.connectType_data.get(spList2.getSelectedItemPosition())));
        boolean enable2 = cbEnalbe2.isChecked();
        if (rbtnSingle.isChecked()) {
            if (ip1.length() != 15 || port1.isEmpty()) {
                toastShow("请填写IP和端口");
                return;
            }
            //一条
            stringBuilder.append("01").append(" ");

            for (int i = 0; i < ip1.split("\\.").length; i++) {
                stringBuilder.append( String.format("%02x ", Integer.parseInt( ip1.split("\\.")[i])));
            }
            //低位在前
            stringBuilder.append( String.format("%04x", Integer.parseInt( port1)).substring(2,4)).append(" ");
            stringBuilder.append( String.format("%04x", Integer.parseInt( port1)).substring(0,2)).append(" ");
            stringBuilder.append( sp1).append(" ");
            stringBuilder.append(enable1 ? "AA" : "55");


        } else {
            if (ip1.length() != 15 || port1.isEmpty() || ip2.length() != 15 || port2.isEmpty()) {
                toastShow("请填写IP和端口");
                return;
            }
            //两条
            stringBuilder.append("02").append(" ");
            //第一条
            for (int i = 0; i < ip1.split("\\.").length; i++) {
                stringBuilder.append( String.format("%02x ", Integer.parseInt( ip1.split("\\.")[i])));
            }
            stringBuilder.append( String.format("%04x", Integer.parseInt( port1)).substring(2,4)).append(" ");
            stringBuilder.append( String.format("%04x", Integer.parseInt( port1)).substring(0,2)).append(" ");
            stringBuilder.append( sp1).append(" ");
            stringBuilder.append(enable1 ? "AA " : "55 ");

            //第二条
            for (int i = 0; i < ip1.split("\\.").length; i++) {
                stringBuilder.append( String.format("%02x ", Integer.parseInt( ip2.split("\\.")[i])));
            }
            stringBuilder.append( String.format("%04x", Integer.parseInt( port2)).substring(2,4)).append(" ");
            stringBuilder.append( String.format("%04x", Integer.parseInt( port2)).substring(0,2)).append(" ");
            stringBuilder.append( sp2).append(" ");
            stringBuilder.append(enable2 ? "AA" : "55" );

        }


        //        String msg = CmdConfig.CMD_23_19 + " " + stringBuilder.substring(0, stringBuilder.length() - 1);
                sendData(stringBuilder.toString());

        Log.e("xxxxxxxx", stringBuilder.toString());
    }




    private void sendData(String data) {
        String cmd = CmdUtils.getCmd(CmdConfig.CMD_23, data);

        BluetoothUtils.send(cmd, new BluetoothUtils.onCallback() {
            @Override
            public void onReceive(String msg) {
                dismissLoadingDialog();

                String[] data = msg.split(" ");
                if (data.length < 18) {
                    ToastUtil.info(msg);
                    return;
                }
                if (data[12].equals(CmdConfig.CMD_23)
                        && data[13].equals(CmdConfig.CMD_23_19)) {
                    if (data[14].equals(CmdConfig.SUCCECC)) {
                        ToastUtil.success("设置成功");
                    } else {
                        ToastUtil.error("设置失败");
                    }

                }


            }

            @Override
            public void onFail(String err) {
                toastShow(err);
                dismissLoadingDialog();
            }
        });
    }




    @OnClick({R.id.btn_nb_1, R.id.btn_6031_1, R.id.btn_5008_1, R.id.btn_fz_1, R.id.btn_nb_2, R.id.btn_6031_2, R.id.btn_5008_2, R.id.btn_fz_2, R.id.btn_set})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_nb_1:
                edtIp1.setText("180.101.147.115");
                edtPort1.setText("5683");
                spList1.setSelection(3);
                break;
            case R.id.btn_6031_1:
                edtIp1.setText("218.019.190.244");
                edtPort1.setText("6031");
                spList1.setSelection(1);
                break;
            case R.id.btn_5008_1:
                edtIp1.setText("218.019.190.244");
                edtPort1.setText("5008");
                spList1.setSelection(1);
                break;
            case R.id.btn_fz_1:
                edtIp1.setText("117.060.157.137");
                edtPort1.setText("5683");
                spList1.setSelection(3);
                break;
            case R.id.btn_nb_2:
                edtIp2.setText("180.101.147.115");
                edtPort2.setText("5683");
                spList2.setSelection(3);
                cbEnalbe2.setChecked(true);
                break;
            case R.id.btn_6031_2:
                edtIp2.setText("218.019.190.244");
                edtPort2.setText("6031");
                spList2.setSelection(1);
                cbEnalbe2.setChecked(true);
                break;
            case R.id.btn_5008_2:
                edtIp2.setText("218.019.190.244");
                edtPort2.setText("5008");
                spList2.setSelection(1);
                cbEnalbe2.setChecked(true);
                break;
            case R.id.btn_fz_2:
                edtIp2.setText("117.060.157.137");
                edtPort2.setText("5683");
                spList2.setSelection(3);
                cbEnalbe2.setChecked(true);
                break;

            case R.id.btn_set:
                                set();

                break;
        }
    }
}
